package cn.yangliu.nacos.comm.oauth;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Objects;

import cn.yangliu.nacos.comm.constant.SecurityConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2019 -12-31
 */
public class Oauth2FeignIntercepter implements RequestInterceptor {

    /**
     * current class instance's member.
     * The Basic auth header.
     */
    private String basicAuthHeader;

    /**
     * Instantiates a new Oauth 2 feign intercepter.
     * allow any class to create a new instance.
     *
     * @param clientId     the client id
     * @param clientSecret the client secret
     */
    public Oauth2FeignIntercepter(String clientId, String clientSecret) {
        this.basicAuthHeader = SecurityConstants.AUTHORIZATION_BASIC + Base64.getEncoder()
                .encodeToString((clientId + ":" + clientSecret).getBytes(StandardCharsets.ISO_8859_1));
    }

    /**
     * Apply.
     *
     * @param requestTemplate the request template
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        String header = getHeader(requestTemplate);
        requestTemplate.header("Content-Type", "application/json; charset=UTF-8");
        requestTemplate.header("Accept", "application/json");
        requestTemplate.header(SecurityConstants.AUTHORIZATION_KEY, header);
    }

    /**
     * Get header string.
     *
     * @param requestTemplate the request template
     * @return the string
     */
    private String getHeader(RequestTemplate requestTemplate){
        String url = requestTemplate.url();
        String target = "?";

        if (url.contains(target)){
            url = url.substring(0, url.lastIndexOf(target));
        }
        String method = requestTemplate.method();
        String header = "";

        // 获取token
        if (Objects.equals("/oauth/token", url) && method.equalsIgnoreCase("POST")){
            header = basicAuthHeader;
        }

        return header;
    }
}
